﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using PropertyManagment.common.lang;
using PropertyManagment.common.utils;
using PropertyManagment.controllers;
using PropertyManagment.entity;
using PropertyManagment.entity.dto;
using PropertyManagment.service;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace PropertyManagment.controllers {

    /// <summary>
    /// 用户控制器
    /// </summary>
    //[ApiController]
    //[Route("[controller]")]
    public class SysUserController : BaseController<SysUser> {

        /// <summary>
        /// 用户列表
        /// </summary>
        /// <param name="username">用户名</param>
        /// <response code="200">返回用户列表</response>
        /// <returns></returns>
        [HttpGet]
        [Route("/sys/user/list")]
        [Authorize(Roles = "sys:user:list")]
        public Result list(string username) {
            Page<SysUser> pageData = sysUserService.page(getPage(),
                //username不为空的时候就查全部
                string.IsNullOrWhiteSpace(username) ? sysUserService.getAll() : sysUserService.getAll().Where(u => u.username.Contains(username)).ToList());

            bool filtration = false;
            pageData.records.ForEach(u => {
                u.sysRoles = sysRoleService.getByUserId(u.id);
                // 找出当前登录的用户是否是超级管理员
                if (u.username.Equals(HttpContext.User.Identity.Name)) {
                    Debug.WriteLine("登录用户");
                    if (u.sysRoles.All(r=>r.name!="超级管理员")) {
                        Debug.WriteLine("启动过滤");
                        filtration = true;
                    }
                } else {
                    Debug.WriteLine("不是登录用户");
                }
            });

            // 过滤掉 没有超级管理员权限的用户不显示超级管理员的用户列表出来
            if (filtration) {
                List<SysUser> sysUsers = sysUserService.getAll().Where(u => u.sysRoles.All(r => !r.name.Equals("超级管理员") && !r.name.Equals("管理员"))).ToList();
                pageData.records = sysUsers;
                pageData.total = sysUsers.Count();
            }

            return Result.succ(pageData);
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="sysUser">用户信息</param>
        /// <response code="200">返回用户信息</response>
        /// <returns></returns>
        [HttpPost]
        [Route("/sys/user/save")]
        [Authorize(Roles = "sys:user:save")]
        public Result save([FromBody] SysUser sysUser) {
            try {
                sysUser.created = DateTime.Now;
                // 默认密码
                sysUser.password = Producer.Encrypt(Const.DEFULT_PASSWORD);
                // 默认头像
                sysUser.avatar = Const.DEFULT_AVATAR;
                sysUserService.add(sysUser);
                return Result.succ(sysUser);
            } catch (Exception e) {
                return Result.fail("添加用户失败，可能该用户名已经存在！");
            }
        }

        /// <summary>
        /// 更新用户
        /// </summary>
        /// <param name="sysUser">用户信息</param>
        /// <response code="200">返回用户信息</response>
        /// <returns></returns>
        [HttpPost]
        [Route("/sys/user/update")]
        [Authorize(Roles = "sys:user:update")]
        public Result update([FromBody] SysUser sysUser) {
            try {
                sysUser.updated = DateTime.Now;
                //if (!string.IsNullOrEmpty(sysUser.password)) { 
                //    sysUser.password = Producer.Encrypt(sysUser.password);
                //}
                sysUserService.update(sysUser);
                return Result.succ(sysUser);
            } catch (Exception e) {
                return Result.fail("编辑用户失败，可能该用户名已经存在！");
            }
        }

        /// <summary>
        /// 单个用户信息
        /// </summary>
        /// <param name="id">用户id</param>
        /// <response code="200">返回用户信息</response>
        /// <response code="404">如果id为空</response>
        /// <returns></returns>
        [HttpGet]
        [Route("/sys/user/info/{id}")]
        [Authorize(Roles = "sys:user:list")]
        public Result info(long id) {
            SysUser sysUser;
            try {
                sysUser = sysUserService.getById(id);
            } catch (Exception e) {
                return Result.fail("找不到该管理员");
            }
            List<SysRole> roles = sysRoleService.getByUserId(id);
            sysUser.sysRoles = roles;
            return Result.succ(sysUser);
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="ids">用户id</param>
        /// <response code="200">删除成功</response>
        /// <returns></returns>
        [HttpPost]
        [Route("/sys/user/delete")]
        [Authorize(Roles = "sys:user:delete")]
        public Result delete([FromBody] long[] ids) {
            sysUserService.deleteByIds(ids);
            sysUserRoleService.deleteList(sysUserRoleService.getAll().Where(ur => ids.Contains(ur.user_id)).ToList());
            return Result.succ("删除成功");
        }

        /// <summary>
        /// 更新用户权限
        /// </summary>
        /// <param name="userId">用户id</param>
        /// <param name="roleIds">角色id</param>
        /// <response code="404">如果id为空</response>
        /// <returns></returns>
        [HttpPost]
        [Route("/sys/user/role/{userId}")]
        [Authorize(Roles = "sys:user:role")]
        public Result rolePerm(long userId, [FromBody] long[] roleIds) {
            List<SysUserRole> userRoles = new List<SysUserRole>();
            roleIds.ToList().ForEach(r => {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.role_id = r;
                sysUserRole.user_id = userId;
                userRoles.Add(sysUserRole);
            });
            sysUserRoleService.deleteList(sysUserRoleService.getAll().Where(ur => ur.user_id == userId).ToList());
            sysUserRoleService.addList(userRoles);
            // 删除缓存
            SysUser sysUser = sysUserService.getById(userId);
            sysUserService.clearUserAuthorityInfo(sysUser.username);
            return Result.succ("");
        }

        /// <summary>
        /// 用户重置密码
        /// </summary>
        /// <param name="userId">用户id</param>
        /// <response code="200">重置成功</response>
        /// <returns></returns>
        [HttpPost]
        [Route("/sys/user/repass")]
        [Authorize(Roles = "sys:user:repass")]
        public Result repass([FromBody] long userId) {
            SysUser sysUser = sysUserService.getById(userId);
            sysUser.password = Producer.Encrypt(Const.DEFULT_PASSWORD);
            sysUser.updated = DateTime.Now;
            sysUserService.update(sysUser);
            return Result.succ("重置成功");
        }

        /// <summary>
        /// 用户更新密码
        /// </summary>
        /// <param name="passDto">密码信息</param>
        /// <response code="200">修改成功</response>
        /// <returns></returns>
        [HttpPost]
        [Route("/sys/user/updatePass")]
        [Authorize]
        public Result updatePass([FromBody] PasswordDto passDto) {
            SysUser sysUser = sysUserService.getByUsername(HttpContext.User.Identity.Name);
            bool matches = Producer.passwordMatches(passDto.currentPass, sysUser.password);
            if (!matches) {
                return Result.fail("旧密码不正确");
            }
            sysUser.password = Producer.Encrypt(passDto.password);
            sysUser.updated = DateTime.Now;
            sysUserService.update(sysUser);
            return Result.succ("修改成功");
        }
    }
}
